import Taro, {useState, useEffect, useCallback, useContext, useRef} from '@tarojs/taro'
import loveLornUser from '../../api/lovelorn-user'
import {View, Text, Icon, Button, Textarea, Image, Camera} from '@tarojs/components'
import {AtTextarea, AtModal, AtIcon} from 'taro-ui'
import './index.scss'
import env from '../../utils/env.json'
import {getGlobalData} from '../../utils/global'

// class RoundProgress extends Component<{}, any> {
function MarriageBoxPage(props) {
  let {isShow, onclose, userInfo} = props
  const [fileImg, setfileImg] = useState([] as string[])
  const [textareaValue, setTextareaValue] = useState('')
  const [isHide, setIshide] = useState(false)
  const [hasStorage, setHasStorage] = useState(false)
  const [keyboardH, setKeyboardH] = useState(-425)
  const textAreaContent = useRef(null)
  useEffect(() => {
    try {
      if (hasStorage) {
        const value = Taro.getStorageSync('Marriage')
        if (value) {
          // console.error('获取数据', 'hasStorage')
          // console.log(value)
          setTextareaValue(value)
        }
      }
    } catch (e) {
      // Do something when catch e	rror
    }
  }, [hasStorage, textAreaContent.current, props.isShow])
  //数据保存
  const handleConfirm = () => {
    setHasStorage(true)
    textAreaContent.current = textareaValue
    // console.log(Taro.getStorage('Marriage'))
    Taro.setStorage({
      key: 'Marriage',
      data: textareaValue,
      success: function() {
        setIshide(false)
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        setEmpty()
      },
    })
    onclose()
  }
  //关闭弹框
  const closebox = () => {
    setHasStorage(false)
    textAreaContent.current = ''
    Taro.removeStorage({
      key: 'Marriage',
      success: function(res) {
        setIshide(false)
        setEmpty()
      },
    })
    onclose()
  }
  //获取文本内容
  const handleChange = e => {
    console.log('获取文本内容')
    setTextareaValue(e)
  }
  //文本获取焦点
  const handleFocus = e => {
    console.log('文本获取焦点')
    console.log(e.detail.height)
    e.detail.height = -425 + e.detail.height
    setKeyboardH(e.detail.height)
  }
  //文本失去焦点
  const handleBlur = e => {
    console.log('文本失去焦点')
    setKeyboardH(-425)
  }
  //清空本地存储图片
  const fileUpdate = e => {
    setfileImg([] as string[])
  }
  //清空本地存储数据
  const setEmpty = () => {
    setfileImg([] as string[])
    setTextareaValue('')
  }
  //提交
  const getSubmitApply = async (file?: string) => {
    try {
      const res = await loveLornUser.marriageSeekingApplys.submitApply({
        seekingContent: textareaValue,
        userPhoto: file,
      })
      if (res) {
        setEmpty()
        onclose()
      }
    } catch (ex) {
      console.error(JSON.parse(ex))
    }
  }
  //上传图片
  const getUploadImage = async () => {
    console.log(fileImg, 'fileImg')
    if (fileImg && fileImg.length) {
      Taro.uploadFile({
        url: `${env.httpBaseUrl}/platform-support/v1.4/pt/uploads/action/upload-image`,
        filePath: fileImg[0],
        name: 'file',
        header: {
          token: userInfo.token,
          userId: userInfo.userId,
          devType: 4,
          tenantId: userInfo.tenantId,
        },
        success(res) {
          const data = res.data
          console.log(JSON.parse(data).data.resourceUrl, 'res')
          getSubmitApply(JSON.parse(data).data.resourceUrl)
        },
      })
    } else {
      getSubmitApply()
    }
  }
  //上传图片显示
  const handleClick = e => {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        setfileImg(res.tempFilePaths)
      },
    })
  }
  //关闭显示弹窗
  const getClickShow = e => {
    setIshide(true)
    // setIsShow(false)
  }

  return (
    props &&
    props.isShow && (
      <View className="MarriageBoxPage">
        <View className="boxBg"></View>
        <View className="boxCent" style={'margin-bottom:' + keyboardH + 'rpx'}>
          <Text className="boxTitle"></Text>
          <View
            className="iconClose"
            onClick={() => {
              setIshide(true)
            }}></View>
          <View className="boxCent-cent">
            <AtTextarea
              maxLength="300"
              placeholder="在这里输入您的征婚信息"
              value={textareaValue}
              onFocus={handleFocus}
              onBlur={handleBlur}
              onChange={handleChange}></AtTextarea>
            {fileImg.length ? (
              <View className="fileImage">
                <Image src={fileImg[0]} />
                <Icon size="20" type="clear" className="iconClose" onClick={fileUpdate} />
              </View>
            ) : (
              <View className="fileBtn" onClick={handleClick}>
                <View className="file-icon">
                  <Icon className="fileIcon"></Icon>
                  {/* <AtIcon value="camera" color="#394650"></AtIcon> */}
                  <View>上传</View>
                </View>
                <View className="boxCent-txt">上传您的生活照</View>
              </View>
            )}
          </View>
          {textareaValue ? (
            <Button
              className="disable-btn submitBtn"
              onClick={() => {
                getUploadImage()
              }}>
              提交
            </Button>
          ) : (
            <Button className="disable-btn" disabled>
              提交
            </Button>
          )}
        </View>
        <AtModal
          isOpened={isHide}
          // title='标题'
          cancelText="不保存"
          confirmText="保存"
          onCancel={closebox}
          onConfirm={handleConfirm}
          content="您的征婚信息暂未提交，是否保存当前信息"
        />
      </View>
    )
  )
}

export default MarriageBoxPage
